import { h, shallowRef, markRaw } from "vue";
import { Addon, type Node, type Graph } from "@antv/x6";
import type { IFlowGraphContext } from "./create";

/**
 * 拖拽面板相关
 * @param context
 */
export default function installStencil(context: Required<IFlowGraphContext>) {
	const stencilEl = shallowRef<HTMLElement | undefined>();

	const stencilKey = "special";

	/**
	 * 面板组件
	 * @returns
	 */
	const StencilComponent = () => h("div", { ref: stencilEl });

	/**
	 * 创建拖拽的面板
	 * @returns
	 */
	const createStencil = (graph: Graph) => {
		if (!stencilEl.value) return;
		const stencil = new Addon.Stencil({
			target: graph,
			stencilGraphWidth: 280,
			// title: "Flowchart",
			// collapsable: true,
			groups: [
				// {
				// 	name: "basic",
				// 	title: "基础节点",
				// 	graphHeight: 260
				// },
				{
					name: stencilKey,
					title: "预定义节点",
					// layoutOptions: {
					//   columns: 1,
					//   marginX: 60,
					// },
					graphHeight: 700
				}
			]
		});
		context.stencil = markRaw(stencil);
		stencilEl.value.appendChild(stencil.container);
		return context.stencil;
	};

	const promise = Promise.resolve();
	const allNodes: (Node | Node.Metadata)[] = [];
	let isFinish = false;
	/**
	 * 将自定义节点添加到面板中
	 * @param nodes
	 * @returns
	 */
	const appendStencil = (nodes: (Node | Node.Metadata)[]) => {
		const { stencil } = context;
		if (!stencil) return;
		allNodes.push(...nodes);
		if (!isFinish) {
			isFinish = true;
			promise
				.then(() => {
					stencil.load(allNodes, stencilKey);
				})
				.finally(() => {
					isFinish = false;
				});
		}
	};

	return { StencilComponent, createStencil, appendStencil, allNodes };
}
